<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

/**
 * Abstract Domain Entity
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel_Domain
 */
abstract class Entity extends DataHolder
{

  /**
   * 
   * @var boolean
   */
  protected $dirty = false;

  /**
   * 
   * @var boolean
   */
  protected $new = true;

  /**
   * 
   * @var EntityDefinition
   */
  protected $def;

  /**
   * 
   * @return array
   */
  public function getFields()
  {
    return $this->def->getFields();
  }

  /**
   * 
   * @return EntityDefinition the definition for this entity
   */
  public function getDefinition()
  {
    if (empty($this->def)) {
      $this->def = DAO::getInstance()->getEntity($this->getName());
    }
    return $this->def;
  }

  /**
   * 
   * @param string $field
   * @return FieldDefinition
   */
  public function getField($field)
  {
    return $this->def->getField($field);
  }

  /**
   * 
   * @return string
   */
  public function getName()
  {
    return get_class($this);
  }

  /**
   * 
   * @return string
   */
  public function getTable()
  {
    if (! $this->def->getTable()) {
      $this->def->setTable(Inflector::tableize($this->getName()));
    }
    return $this->def->getTable();
  }

  /**
   * 
   * @return boolean
   */
  public function isNew()
  {
    return $this->new;
  }

  /**
   * 
   * @return boolean
   */
  public function isDirty()
  {
    return $this->dirty;
  }

  /**
   * Commit changes to data.
   * 
   * @return void
   */
  public function commit()
  {
    parent::commit();
    
    $this->dirty = false;
    $this->new = false;
  }

  public function getModified()
  {
    return $this->getAll();
  }

  public function _set($name, $value)
  {
    parent::_set($name, $value);
    $this->dirty = (boolean) count($this->modified);
  }

}

?>